package com.zyy.seckill.controller;

import com.zyy.seckill.entity.User;
import com.zyy.seckill.service.IGoodsService;
import com.zyy.seckill.service.IUserService;
import com.zyy.seckill.vo.DetailVo;
import com.zyy.seckill.vo.GoodsVo;
import com.zyy.seckill.vo.RespBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.context.WebContext;
import org.thymeleaf.spring5.ISpringTemplateEngine;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * 商品
 * <p>
 * windows 优化前:QPS: 1931.8196
 *          缓存QPS:3500
 *
 * @Author: zyy
 * @DateTime: 2021/10/3 21:52
 */
@Controller
@RequestMapping("/goods")
public class GoodsController {

    @Autowired
    private IUserService userService;

    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private ThymeleafViewResolver thymeleafViewResolver;


    /**
     *   携带用户信息跳转商品页(通俗易懂版本)
     * @param session
     * @param model
     * @param ticket
     * @return

     @RequestMapping("/toList") public String toList(HttpSession session, //获取session
     HttpServletRequest request,
     HttpServletResponse response,
     Model model,       // 传参
     @CookieValue("userTicket") String ticket){// 获取cookie
     if (!StringUtils.hasLength(ticket)){
     return "login";
     }
     //        User user = (User)session.getAttribute(ticket);
     User user = userService.getUserByCookie(ticket, request, response);
     if (null ==user){
     return "login";
     }
     model.addAttribute("user",user);
     return "goodsList";
     }
     */

    /**
     * 优化版  跳转商品列表页(v2.0)
     *
     * @param user
     * @param model
     * @return
     */
    @RequestMapping(value = "/toList", produces = "text/html;charset=utf-8")// 传输整个页面而不单单的进行页面的跳转
    @ResponseBody
    public String toList(User user, Model model,
                         HttpServletRequest request,
                         HttpServletResponse response) {

        // 从redis中获取页面,如果不为空,就直接返回页面
        ValueOperations operations = redisTemplate.opsForValue();
        String html = (String) operations.get("goodsList");
        if (StringUtils.hasLength(html)){
            return html;
        }

        /**
         * 以下页面为空的操作
         */

        // 参数设置
        model.addAttribute("user", user);
        model.addAttribute("goodsList", goodsService.findGoodsVo());

        // 如果为空就手动渲染并且给放到redis缓存中(并不使用spring渲染)
        WebContext webContext = new WebContext(request,response, request.getServletContext(), // 请求.页面模板信息,地址,参数
                request.getLocale(),model.asMap());

         html = thymeleafViewResolver
                .getTemplateEngine()
                .process("goodsList", webContext);// 通过构造出来的webContext进行页面渲染

        if (StringUtils.hasLength(html)){ // 渲染成功就存储redis中并且设置时间
            operations.set("goodsList",html,1, TimeUnit.MINUTES);//设置失效时间
        }
        return html;

//        return "goodsList";
    } //获取session


    /**
     * @param user
     * @param model
     * @return
     */
    @RequestMapping(value = "/toDetail/{goodsId}",produces = "text/html;charset=utf-8") //v2.0缓存url地址
    @ResponseBody
    public String toDetails(User user,Model model,  @PathVariable("goodsId") long goodsId, HttpServletRequest request,HttpServletResponse response) {// 传参

//        User user = (User)session.getAttribute(ticket);

        ValueOperations valueOperations = redisTemplate.opsForValue(); // 判断页面是否被缓存
        String html = (String)valueOperations.get("goodsDetail"+goodsId);
        if (StringUtils.hasLength(html)){
            return html;
        }

        GoodsVo goodsVo = goodsService.findGoodsVoById(goodsId);
        model.addAttribute("user", user);
        model.addAttribute("goods", goodsVo);
        Date startDate = goodsVo.getStartDate();
        Date endDate = goodsVo.getEndDate();
        Date nowDate = new Date();
//        System.out.println(startDate +": 开始,结束 : " +endDate);

        int secKillStatus; // 秒杀状态
        int remainSeconds; // 秒杀倒计时
        if (nowDate.before(startDate)) { // 判断秒杀状态 未开始
            secKillStatus = 0;
            remainSeconds = (int) ((startDate.getTime() - nowDate.getTime()) / 1000);
        } else if (nowDate.after(endDate)) { // 秒杀结束
            secKillStatus = 2;
            remainSeconds = -1;
        } else { // 正在进行
            secKillStatus = 1;
            remainSeconds = 0;
        }

//        System.out.println(user + "   " + goodsVo);
        model.addAttribute("secKillStatus", secKillStatus);
        model.addAttribute("remainSeconds", remainSeconds);
        // 手动渲染
        WebContext webContext = new WebContext(request,response,request.getServletContext(),request.getLocale(),model.asMap());
        ISpringTemplateEngine engine = thymeleafViewResolver.getTemplateEngine();
        html = engine.process("goodsDetail", webContext);
        if (StringUtils.hasLength(html)){
            valueOperations.set("goodsDetail"+goodsId,html,1,TimeUnit.MINUTES);
        }
        return html;
    }


    /**
     * @param user
     * @param model
     * @return
     */
    @RequestMapping("/detail/{goodsId}")
    @ResponseBody
    public RespBean toDetails2(User user, Model model, @PathVariable("goodsId") long goodsId) {// 传参

        GoodsVo goodsVo = goodsService.findGoodsVoById(goodsId);

        Date startDate = goodsVo.getStartDate();
        Date endDate = goodsVo.getEndDate();
        Date nowDate = new Date();

        int secKillStatus; // 秒杀状态
        int remainSeconds; // 秒杀倒计时
        if (nowDate.before(startDate)) { // 判断秒杀状态 未开始
            secKillStatus = 0;
            remainSeconds = (int) ((startDate.getTime() - nowDate.getTime()) / 1000);
        } else if (nowDate.after(endDate)) { // 秒杀结束
            secKillStatus = 2;
            remainSeconds = -1;
        } else { // 正在进行
            secKillStatus = 1;
            remainSeconds = 0;
        }
        DetailVo detail = new DetailVo();
        detail.setUser(user);
        detail.setGoodsVo(goodsVo);
        detail.setSecKillStatus(secKillStatus);
        detail.setRemainSeconds(remainSeconds);

        return  RespBean.success(detail);
    }


}
